#include <iostream>
#include <unistd.h>
#include <cstdio>
#include <cstdlib>
#include <string>
#include <sys/types.h>
#include <sys/wait.h>

//实现进程间通信：子写父读
int main()
{
    int pipefd[2] = {0};
    int n = pipe(pipefd); // 1、创建管道
    // 成功返回0，失败返回-1
    //  if(n == 0)
    //  {
    //      printf("creat pipe success: pipefd[0]: %d, pipefd[1]: %d\n", pipefd[0], pipefd[1]);
    //  }

    pid_t id = fork();
    if (id < 0)
    {
        perror("fork");
        exit(1);
    }
    if (id == 0)
    {
        // 子进程
        // 关闭不需要端口
        close(pipefd[0]); // 子进程执行写操作，关闭读端口
        std::string str = "hello father, I'm son, ";
        std::string self = std::to_string(getpid());
        int cnt = 1;
        std::string message = str + ", " + self + ", ";
        while (true)
        {
            // 写操作
            message += std::to_string(cnt++);
            write(pipefd[1], message.c_str(), message.size());
            sleep(1);
        }
    }
    else
    {
        // 父进程
        // 关闭不需要端口
        close(pipefd[1]); // 父进程执行读操作，关闭写端口
        while (true)
        {
            char inbuffer[1024] = {0};
            ssize_t n = read(pipefd[0], inbuffer, sizeof(inbuffer) - 1);//读取数据
            if (n > 0)
            {
                inbuffer[n] = 0;
                std::cout << "clinet->father: " << inbuffer << std::endl;
            }
        }

        pid_t rid = waitpid(id, nullptr, 0);
        (void)rid;
    }

    return 0;
}